/**
 * @Date 2024/12/15 13:30
 * @Created by 衡盛永
 */

package org.example.deploy.exception;

import org.example.deploy.dto.ResultDto;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {
    // 全局异常处理
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultDto exceptionHandler(Exception e) {
        e.printStackTrace();
        return ResultDto.error(201, "");
    }

    // 特定异常处理
//    @ExceptionHandler(value = ArithmeticException.class)
//    @ResponseBody
//    public Result exceptionHandler(ArithmeticException e) {
//        e.printStackTrace();
//        return Result.response(201, "ArithmeticException");
//    }

    // 自定义异常处理

    /**
     * 使用自定义异常需要手动抛出异常
     * try {
     * int a = 9 / 0;
     * } catch (Exception e) {
     * e.printStackTrace();
     * throw new CustomException(20001, "CustomException");
     * }
     */
    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public ResultDto exceptionHandler(CustomException e) {
        e.printStackTrace();
        return ResultDto.error(e.getCode(), e.getMsg());
    }
}